Easy2Siksha.com
Note: GNDU has shuffled some subjects between semesters (e.g., C Programming from 1st Sem to 3rd Sem), but the
syllabus and most questions are still similar, so don’t get confused you are studying from the correct papers.
GNDU Question Paper-2025
Bachelor of Computer Application (BCA) (Hons.)
3
rd
Semester (Batch 2024-28) (CBGS)
INTRODUCTION TO PROGRAMMING USING PYTHON
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1. (a) Discuss the features of Python for problem solving. Write a simple Python program that
takes character input from a user.
(b) Explain the core components of Python program structure.
2. (a) How Python IDE and Interpreter are used for execution? Explain.
(b) Explain the significance of comments and indentation using Python.
SECTION-B
3.(a) Explain Data types of Python and illustrate their use.
(b) Illustrate the use of For control structure through Python program.
4.(a) Write a program in Python to find count of odd numbers from a list of numbers.
(b) How break and continue statements are used by Python programs? Illustrate.
SECTION-C
Easy2Siksha.com
5. (a) Discuss the process of using Python modules and their purpose.
(b) How recursive functions are used for problem solving using Python? Illustrate.
6.(a) How functions are called and passed by Python programs? Illustrate.
(b) Discuss the role of exception handling and its types.
SECTION-D
7 Discuss the following with examples:
(a) Strings processing
(b) Data processing
8. How the files are processed using Python? Discuss the use of write() and writelines() functions.
Easy2Siksha.com
GNDU Answer Paper-2025
Bachelor of Computer Application (BCA) (Hons.)
3
rd
Semester (Batch 2024-28) (CBGS)
INTRODUCTION TO PROGRAMMING USING PYTHON
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1. (a) Discuss the features of Python for problem solving. Write a simple Python program that
takes character input from a user.
(b) Explain the core components of Python program structure.
Ans: 1. (a) Discuss the Features of Python for Problem Solving. Write a Simple Python
Program that Takes Character Input from a User.
(b) Explain the Core Components of Python Program Structure.
Python is one of the most popular programming languages in the world today. It is widely
used by beginners, students, software developers, scientists, and even large companies like
Google, Netflix, and Instagram. The main reason behind its popularity is that Python is easy
to learn, easy to write, and easy to understand.
Imagine that programming is like giving instructions to a robot. If your instructions are
confusing, the robot will not understand them. Python allows us to give instructions in a
very simple and readable way. This makes Python one of the best languages for problem
solving.
What is Problem Solving in Python?
Problem solving means finding a solution to a problem using logical thinking and
programming.
For example:
Easy2Siksha.com
Finding the average marks of students.
Calculating electricity bills.
Checking whether a number is even or odd.
Managing employee records.
Building websites or games.
Python helps us solve these problems by writing short and simple programs.
Features of Python for Problem Solving
Python provides many features that make solving problems easier.
1. Easy to Learn
Python has a simple syntax that looks similar to English.
Example:
print("Hello")
Even a beginner can understand what this program does.
Unlike many other programming languages, Python uses fewer symbols and less
complicated code.
2. Easy to Read
Python programs are clean and readable.
Example:
age = 20
if age >= 18:
print("Eligible")
Anyone reading this program can quickly understand its purpose.
Readable code also makes debugging easier.
3. Easy to Write
Easy2Siksha.com
Python requires fewer lines of code compared to languages like C or Java.
For example, printing a message takes only one line.
print("Welcome")
Less code means fewer chances of making mistakes.
4. Interpreted Language
Python is an interpreted language.
This means:
The program is executed line by line.
No separate compilation is required.
Advantages
Easy testing
Faster debugging
Immediate output
5. Portable
Python programs can run on different operating systems.
Examples:
Windows
Linux
macOS
The same program works on different computers with little or no changes.
6. Free and Open Source
Python is completely free.
Anyone can:
Download it
Easy2Siksha.com
Install it
Modify it
Share it
There is no license fee.
7. Large Standard Library
Python provides thousands of built-in modules.
Examples:
Mathematics
Date and Time
File Handling
Internet Programming
This saves a lot of programming effort.
8. Supports Multiple Programming Styles
Python supports:
Procedural Programming
Object-Oriented Programming (OOP)
Functional Programming
Therefore, programmers can solve problems using different approaches.
9. Automatic Memory Management
Python automatically manages memory.
The programmer does not need to free unused memory manually.
This reduces programming errors.
10. Huge Community Support
Millions of developers use Python.
Easy2Siksha.com
Whenever you face a problem, you can find:
Tutorials
Videos
Documentation
Community support
This makes learning much easier.
Diagram: Features of Python
PYTHON
┌─────────────────────────────────┐
│ │
Easy to Learn Easy to Read
│ │
Portable Interpreted
Free & Open Source Large Library
│ │
Automatic Memory Multiple Programming
Management Styles
Simple Python Program for Character Input
Python provides the input() function to accept input from the user.
Program
character = input("Enter a character: ")
print("You entered:", character)
Output
Enter a character: A
You entered: A
Explanation
Line 1
character = input("Enter a character: ")
Easy2Siksha.com
The computer asks the user to enter one character.
Suppose the user enters:
A
The character is stored in the variable character.
Line 2
print("You entered:", character)
The computer displays the entered character.
Output:
You entered: A
Flow Diagram of the Program
Start
Ask user to enter character
Store character in variable
Display entered character
Stop
(b) Core Components of Python Program Structure
Every Python program is made up of several important parts called core components.
Think of a Python program like a house.
A house has:
Foundation
Walls
Doors
Easy2Siksha.com
Windows
Roof
Similarly, a Python program has different building blocks.
Diagram of Python Program Structure
Python Program
┌──────────────────────────────┐
│ │ │
Variables Input Output
│ │ │
Data Types Operators Statements
│ │
Functions Control Statements
Loops
1. Comments
Comments explain the program.
Python ignores comments while running the program.
Example:
# This program prints Hello
print("Hello")
Comments help others understand the code.
2. Variables
Variables store information.
Example:
name = "Rahul"
age = 20
Here,
Easy2Siksha.com
name stores text.
age stores a number.
3. Data Types
A data type tells Python what kind of value is stored.
Common data types:
Data Type
Example
Integer
10
Float
12.5
String
"Python"
Boolean
True
Example:
marks = 95
price = 55.75
city = "Delhi"
passed = True
4. Input
Input means taking information from the user.
Example:
name = input("Enter your name:")
The computer waits until the user enters something.
5. Output
Output means displaying information.
Example:
print("Welcome")
The message appears on the screen.
Easy2Siksha.com
6. Operators
Operators perform calculations.
Examples:
+
-
*
/
%
Program:
a = 10
b = 5
print(a + b)
Output:
15
7. Statements
Statements are instructions executed one after another.
Example:
x = 5
y = 10
print(x + y)
Each line is a statement.
8. Decision Making (if Statement)
Sometimes programs need to make decisions.
Example:
age = 18
if age >= 18:
print("Adult")
Easy2Siksha.com
Python checks the condition before printing the result.
9. Loops
Loops repeat the same work multiple times.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Loops save time by avoiding repeated code.
10. Functions
Functions are reusable blocks of code.
Example:
def greet():
print("Welcome")
greet()
Instead of writing the same code many times, we create a function once and call it
whenever needed.
Complete Structure Example
# Program to greet user
name = input("Enter your name: ")
def greet(user):
Easy2Siksha.com
print("Welcome", user)
greet(name)
This program contains:
Comment
Variable
Input
Function
Output
All the important components work together.
Real-Life Analogy
Imagine you are making a cup of tea:
1. Ingredients → Data (variables and data types)
2. Recipe → Program logic (statements)
3. Stove → Python Interpreter (executes the code)
4. Steps → Control statements and loops
5. Special method → Functions
6. Finished tea → Output
Just as every step is important to prepare good tea, every component of a Python program
is important to create a correct and efficient program.
Conclusion
Python is an excellent programming language for problem solving because it is simple,
readable, portable, free, and supported by a large collection of built-in libraries. These
features help beginners and professionals write efficient programs with less effort. A basic
Python program can easily accept user input using the input() function and display
results with the print() function. Understanding the core components of a Python
programsuch as comments, variables, data types, input/output, operators, statements,
decision-making, loops, and functionsprovides a strong foundation for writing logical and
well-structured programs. Mastering these concepts enables students to solve real-world
problems confidently and build more advanced Python applications in the future.
Easy2Siksha.com
2. (a) How Python IDE and Interpreter are used for execution? Explain.
(b) Explain the significance of comments and indentation using Python.
Ans: Q2. (a) How Python IDE and Interpreter are used for execution? Explain.
(b) Explain the significance of comments and indentation using Python.
Python is one of the world's most popular programming languages because it is simple, easy
to learn, and easy to read. Unlike many programming languages that require complicated
setup, Python allows beginners to write and execute programs with very little effort. Before
writing Python programs, it is important to understand how Python executes a program
and why comments and indentation are so important.
Imagine you want to write a letter. You first need a notebook and a pen to write it. After
writing, someone reads your letter and understands its meaning. Python works in a similar
way. You write your program using an IDE, and the Interpreter reads your program line by
line and executes it.
(a) Python IDE and Interpreter Used for Execution
What is Python?
Python is a high-level, interpreted programming language developed by Guido van Rossum
in 1991. It is used for:
Web Development
Artificial Intelligence (AI)
Machine Learning
Data Science
Automation
Software Development
Game Development
Python is famous because its syntax is close to normal English.
Example:
print("Hello World")
This single line displays:
Hello World
What is an IDE?
Easy2Siksha.com
IDE stands for Integrated Development Environment.
An IDE is a software application that provides everything needed to write, edit, run, and
debug Python programs in one place.
Think of an IDE as a complete classroom where everything required for learning is already
available.
Instead of opening different software for writing code, saving files, and running programs,
an IDE combines all these features into one application.
Main Functions of an IDE
An IDE helps the programmer by providing:
Code Editor
Run Button
Syntax Highlighting
Auto-completion
Error Detection
Debugging Tools
File Management
Popular Python IDEs
Some commonly used Python IDEs are:
IDLE (comes with Python)
PyCharm
Visual Studio Code (VS Code)
Spyder
Jupyter Notebook
Thonny
Among beginners, IDLE is the easiest.
Features of Python IDE
1. Code Editor
It allows users to write Python code.
Example:
Easy2Siksha.com
print("Welcome")
2. Syntax Highlighting
Different parts of code appear in different colors.
Example:
Keywords → Blue
Strings → Green
Numbers → Black
This improves readability.
3. Auto-complete
The IDE suggests commands while typing.
For example:
When you type
pri
It automatically suggests
print()
This saves time.
4. Error Detection
If a mistake is made, the IDE highlights the error before execution.
5. Debugging
Debugging helps find and remove mistakes (bugs).
The programmer can execute code step by step.
Easy2Siksha.com
6. Run Program
Most IDEs have a Run button that executes the Python program instantly.
What is a Python Interpreter?
A Python Interpreter is a software that reads Python code, understands it, and executes it.
Unlike languages such as C or C++, Python does not first convert the whole program into
machine language.
Instead, it executes the program line by line.
That is why Python is called an interpreted language.
Role of the Interpreter
The interpreter performs three important tasks:
Step 1: Read
It reads one line of code.
Example:
print("Python")
Step 2: Translate
It converts that line into machine-understandable instructions.
Step 3: Execute
It performs the instruction and immediately displays the output.
Output:
Python
The interpreter repeats these three steps until the program finishes.
Easy2Siksha.com
Program Execution Process
The execution process can be understood using the following diagram.
Write Python Program
Save the Program (.py)
Open in Python IDE
Click Run / Execute Program
Python Interpreter Reads Code
Executes Code Line by Line
Output Displayed on Screen
Example of Execution
Program:
a = 5
b = 10
c = a + b
print(c)
Execution:
Line 1
a = 5
Interpreter stores 5.
Line 2
b = 10
Stores 10.
Easy2Siksha.com
Line 3
c = a + b
Adds the values.
Line 4
print(c)
Displays
15
The interpreter executes each line one after another.
Advantages of Python Interpreter
Easy to use
Executes code immediately
Easier debugging
Portable across operating systems
Suitable for beginners
No separate compilation step
(b) Significance of Comments and Indentation in Python
A good Python program is not only correct but also easy to understand. Two important
features that improve readability are comments and indentation.
What are Comments?
Comments are lines written inside a program that are ignored by the Python interpreter.
They are written only for humans.
Comments explain what the code is doing.
Easy2Siksha.com
Why are Comments Important?
Suppose you write a program today.
After six months, you open it again.
Without comments, you may forget why certain code was written.
Comments make programs easier to understand.
Types of Comments
1. Single-Line Comment
It starts with #.
Example:
# Calculate total marks
marks = 450
Python ignores the first line.
2. Multi-Line Comment
Python uses triple quotes.
Example:
"""
This program
calculates
student marks.
"""
Advantages of Comments
1. Easy Understanding
Comments explain the purpose of the code.
Easy2Siksha.com
2. Better Maintenance
Future modifications become easier.
3. Teamwork
Other programmers can understand the program quickly.
4. Documentation
Comments act as documentation for the program.
5. Debugging
They help identify different sections of code.
What is Indentation?
Indentation means leaving spaces at the beginning of a line.
Most programming languages use braces { } to define blocks of code.
Python uses indentation instead of braces.
This makes Python clean and readable.
Why is Indentation Important?
Indentation tells Python:
Which statements belong together.
Where a block of code starts.
Where a block of code ends.
Without proper indentation, Python produces an IndentationError.
Easy2Siksha.com
Example of Correct Indentation
age = 20
if age >= 18:
print("Eligible to Vote")
Output
Eligible to Vote
The print() statement is indented, showing that it belongs to the if block.
Incorrect Indentation
age = 20
if age >= 18:
print("Eligible")
Output
IndentationError
Python expects the statement after if to be indented. Since it is not, the program stops with
an error.
Where is Indentation Used?
Indentation is required in many Python structures, such as:
if
else
for
while
function
class
try
except
Example:
for i in range(3):
print(i)
Easy2Siksha.com
Output:
0
1
2
The indented print(i) belongs to the for loop.
Importance of Indentation
Makes code neat and organized.
Defines code blocks clearly.
Improves readability.
Prevents logical mistakes.
Mandatory in Python; programs cannot run correctly without it.
Difference Between Comments and Indentation
Comments
Indentation
Used to explain the code.
Used to define code blocks.
Ignored by the interpreter.
Read and enforced by the interpreter.
Improve understanding for programmers.
Controls how the program executes.
Start with # or use triple quotes """ """.
Created using spaces (commonly 4 spaces).
Optional but highly recommended.
Mandatory in Python.
Conclusion
Python is easy to learn because of its simple syntax and readable structure. A Python IDE
provides all the necessary tools to write, edit, debug, and execute programs efficiently,
while the Python Interpreter reads the code line by line, translates it into machine-
understandable instructions, and executes it immediately. Comments help programmers
explain the purpose of the code, making it easier to understand, maintain, and debug,
whereas indentation is a mandatory feature in Python that defines the structure of
programs and ensures correct execution. Together, the IDE, interpreter, comments, and
indentation make Python one of the most beginner-friendly and powerful programming
languages available today.
Easy2Siksha.com
SECTION-B
3.(a) Explain Data types of Python and illustrate their use.
(b) Illustrate the use of For control structure through Python program.
Ans: 3(a) Explain Data Types of Python and Illustrate Their Use.
3(b) Illustrate the Use of for Control Structure Through a Python Program.
Python is one of the easiest programming languages in the world. One of the main reasons
behind its popularity is that it uses simple English-like syntax. Before writing any Python
program, it is important to understand data types because every program works with some
kind of data. Similarly, to perform the same task repeatedly without writing the same code
again and again, Python provides control structures, such as the for loop.
(a) Data Types of Python
A data type tells Python what kind of value a variable is storing. Just as we use different
containers for different things (a bottle for water, a box for books, and a wallet for money),
Python also stores different kinds of information using different data types.
Diagram of Python Data Types
Python Data Types
┌───────────────────────────────────────────────────┐
│ │ │ │ │
Numeric Sequence Boolean Set Type Dictionary
│ │ │ │ │
int string(str) True set dict
float list False
complex tuple
1. Integer (int)
An integer stores whole numbers without any decimal point.
Examples
5
100
-25
Easy2Siksha.com
age = 20
marks = 95
print(age)
print(marks)
Output
20
95
Use: Used for counting students, marks, age, roll numbers, etc.
2. Float (float)
A float stores numbers that contain decimal values.
Examples
45.5
3.14
98.75
price = 199.99
temperature = 36.5
print(price)
print(temperature)
Output
199.99
36.5
Use: Used for height, weight, percentage, temperature, prices, etc.
3. Complex (complex)
A complex number contains a real part and an imaginary part.
Example:
x = 3 + 4j
print(x)
Output
Easy2Siksha.com
(3+4j)
Use: Mainly used in scientific calculations and engineering.
4. String (str)
A string stores text or characters.
Strings are written inside single (' ') or double (" ") quotation marks.
Example:
name = "Rahul"
college = "GNDU"
print(name)
print(college)
Output
Rahul
GNDU
Use: Used for names, addresses, messages, emails, etc.
5. List (list)
A list stores multiple values in one variable.
Lists are enclosed inside square brackets [ ].
Example:
subjects = ["English", "Python", "Math"]
print(subjects)
Output
['English', 'Python', 'Math']
Features
Ordered
Changeable (Mutable)
Can store different data types
Easy2Siksha.com
6. Tuple (tuple)
A tuple is similar to a list but cannot be changed after creation.
It uses parentheses ( ).
Example:
days = ("Monday", "Tuesday", "Wednesday")
print(days)
Output
('Monday', 'Tuesday', 'Wednesday')
Use: Used when data should remain fixed.
7. Set (set)
A set stores unique values only.
Duplicate values are automatically removed.
Example:
numbers = {10, 20, 20, 30}
print(numbers)
Output
{10, 20, 30}
Use: Used when duplicate values are not allowed.
8. Dictionary (dict)
A dictionary stores data as key-value pairs.
Example:
student = {
"Name": "Aman",
"Age": 20,
"Marks": 88
Easy2Siksha.com
}
print(student)
Output
{'Name': 'Aman', 'Age': 20, 'Marks': 88}
Use: Used for storing complete information about a person or object.
9. Boolean (bool)
A Boolean data type has only two values:
True
False
Example:
passed = True
print(passed)
Output
True
Use: Used for decision making and checking conditions.
Summary Table
Data Type
Stores
Example
int
Whole numbers
25
float
Decimal numbers
98.5
complex
Complex numbers
2+3j
str
Text
"Python"
list
Multiple values (changeable)
[1,2,3]
tuple
Multiple values (fixed)
(1,2,3)
set
Unique values
{1,2,3}
dict
Key-value pairs
{"Name":"Rahul"}
bool
True/False values
True
(b) for Control Structure in Python
Easy2Siksha.com
Sometimes we need to repeat the same task many times.
For example:
Print numbers from 1 to 10.
Display names of students.
Calculate the total marks of many students.
Instead of writing the same statement again and again, Python provides the for loop.
A for loop repeats a block of code for each item in a sequence (such as a string, list, tuple, or
a range of numbers). It is useful when the number of repetitions is already known.
Working of for Loop
Start
Initialize Loop
Take First Value
Execute Statements
More Values Left?
│ │
Yes No
│ │
▼ ▼
Next Value End
Syntax
for variable in sequence:
statements
Example 1: Print Numbers from 1 to 5
for i in range(1, 6):
print(i)
Output
Easy2Siksha.com
1
2
3
4
5
Explanation:
range(1, 6) generates the numbers 1, 2, 3, 4, and 5.
The variable i takes one value at a time.
print(i) prints each value.
Example 2: Print Student Names
students = ["Aman", "Rahul", "Simran"]
for name in students:
print(name)
Output
Aman
Rahul
Simran
Here, the loop visits each element of the list one by one and prints it.
Example 3: Find the Sum of Numbers
total = 0
for i in range(1, 6):
total = total + i
print("Total =", total)
Output
Total = 15
This program adds the numbers 1, 2, 3, 4, and 5 to produce the final sum.
Easy2Siksha.com
Advantages of for Loop
Reduces repetition of code.
Makes programs shorter and easier to understand.
Saves time and effort.
Helps process lists, strings, tuples, and other collections efficiently.
Improves code readability and maintenance.
Conclusion
Python data types define the kind of information stored in variables, such as numbers, text,
lists, sets, dictionaries, and Boolean values. Choosing the correct data type makes programs
accurate, efficient, and easier to manage.
The for control structure is one of the most useful looping mechanisms in Python. It
automatically repeats a block of code for each item in a sequence or over a range of values,
eliminating the need to write repetitive code. Together, data types and the for loop form
the foundation of Python programming and are essential concepts for writing clear,
efficient, and reliable programs.
4.(a) Write a program in Python to find count of odd numbers from a list of numbers.
(b) How break and continue statements are used by Python programs? Illustrate.
Ans: 4(a) Write a program in Python to find the count of odd numbers from a list of
numbers.
(b) How are break and continue statements used in Python programs? Illustrate.**
This question tests three important Python concepts:
1. Lists
2. Odd numbers and counting them
3. The break and continue statements
Let's understand each topic in the simplest way.
Part (a): Program to Count Odd Numbers in a List
Imagine you are a teacher checking the roll numbers of students.
Suppose the roll numbers are:
Easy2Siksha.com
[10, 15, 22, 37, 40, 51]
Your task is to count only the odd numbers.
You don't need to add them.
You don't need to print every number.
You only need to answer:
"How many odd numbers are there?"
What is a List?
A list is simply a collection of items stored together.
Think of it as a basket.
Basket
+-------------------------+
| 10 15 22 37 40 51 |
+-------------------------+
In Python:
numbers = [10, 15, 22, 37, 40, 51]
This stores six numbers inside one variable.
What is an Odd Number?
An odd number is a number that cannot be divided equally by 2.
Examples:
1 Odd
3 Odd
5 Odd
7 Odd
9 Odd
2 Even
4 Even
Easy2Siksha.com
6 Even
8 Even
Python checks odd numbers using:
number % 2 != 0
Here,
% means remainder
If remainder is not zero, the number is odd.
Example:
15 ÷ 2
Quotient = 7
Remainder = 1
15 % 2 = 1
Therefore,
15 is Odd.
Step-by-Step Working
Suppose the list is:
[5, 8, 11, 20, 25]
Python checks every number one by one.
Start
|
V
5 → Odd → Count = 1
|
8 → Even → Ignore
|
11 → Odd → Count = 2
|
Easy2Siksha.com
20 → Even → Ignore
|
25 → Odd → Count = 3
|
Finish
Answer = 3
Python Program
numbers = [5, 8, 11, 20, 25]
count = 0
for num in numbers:
if num % 2 != 0:
count = count + 1
print("Number of odd numbers:", count)
Output
Number of odd numbers: 3
Explanation
Store numbers in a list.
Create a variable count and set it to 0.
Visit every number using a for loop.
Check whether the number is odd.
If it is odd, increase the count by 1.
Finally, print the total count.
Part (b): Break and Continue Statements
Python loops normally run until every item is processed.
Sometimes we want to:
Easy2Siksha.com
Stop the loop immediately.
Skip one particular item.
Python provides two special statements:
break
continue
Although both are used inside loops, their jobs are different.
1. Break Statement
The word break means stop immediately.
Imagine you are searching for your friend in a classroom.
Student 1
Student 2
Student 3
Friend Found!
Stop Searching
Once you find your friend, you don't need to check the remaining students.
This is exactly what break does.
Diagram
Loop Starts
|
Item 1
|
Item 2
|
Condition True
Easy2Siksha.com
|
BREAK
|
Loop Ends
Everything after break is skipped.
Example
for i in range(1, 6):
if i == 4:
break
print(i)
Output
1
2
3
When Python reaches 4, the loop stops immediately.
2. Continue Statement
The word continue means
"Skip this step and move to the next one."
Imagine your teacher checks homework.
Student 1
Student 2
Student 3 Absent
Skip Student 3
Check Student 4
Check Student 5
Easy2Siksha.com
The teacher does not stop checking.
Only one student is skipped.
That is exactly what continue does.
Diagram
Loop Starts
|
Item 1
|
Item 2
|
Condition True
|
CONTINUE
|
Next Item
|
Loop Continues
Example
for i in range(1, 6):
if i == 3:
continue
print(i)
Output
1
2
Easy2Siksha.com
4
5
Here,
Number 3 is skipped.
The loop continues with 4 and 5.
Difference Between break and continue
Break
Stops the entire loop immediately.
No further iterations are executed.
Used when the required result is found.
Exits the loop completely.
Real-Life Example
Imagine you are checking answer sheets.
Using break
If the principal announces that the exam is cancelled, you stop checking all papers
immediately.
This is break.
Using continue
One answer sheet is damaged, so you skip it and continue checking the remaining papers.
This is continue.
Conclusion
In Python, a list stores multiple values in one place, making it easy to process many numbers
together. To count odd numbers, the program checks each number using the condition
number % 2 != 0; whenever the condition is true, a counter is increased by one. The break
statement is used to terminate a loop immediately when a specific condition is met, saving
unnecessary work. In contrast, the continue statement skips only the current iteration and
allows the loop to continue processing the remaining items. Understanding these concepts
is essential because they help write Python programs that are organized, efficient, and easy
to understand.
Easy2Siksha.com
SECTION-C
5. (a) Discuss the process of using Python modules and their purpose.
(b) How recursive functions are used for problem solving using Python? Illustrate.
Ans: 5. (a) Discuss the process of using Python modules and their purpose.
Python is a very powerful programming language. One of the biggest reasons for its
popularity is modules. Instead of writing every piece of code yourself, Python allows you to
use ready-made collections of functions called modules.
Think of Python as a large toolbox.
A toolbox contains different tools such as a hammer, screwdriver, and wrench.
You don't make these tools every time you need themyou simply take the required
one and use it.
Similarly, Python provides many modules that already contain useful functions.
So, a Python module is simply a file that contains Python code (functions, variables, and
classes) which can be reused in other programs.
Purpose of Python Modules
Modules make programming much easier and faster. Their main purposes are:
1. Code Reusability
Instead of writing the same code repeatedly, you write it once inside a module and use it
whenever needed.
Example:
Suppose you create a module that calculates GST. You can use the same module in many
billing programs.
2. Saves Time
Many useful modules are already available in Python.
For example:
math → Mathematical calculations
Easy2Siksha.com
random → Generate random numbers
datetime → Work with dates and time
os → Interact with the operating system
Instead of creating these functions yourself, you simply import the module.
3. Better Organization
Large programs become easier to manage because related functions are kept together
inside separate files.
Example:
Student Project
── login.py
── marks.py
── fees.py
└── main.py
Each file performs a different task.
4. Easy Maintenance
If there is an error in one module, you only need to fix that module instead of the entire
project.
Process of Using Python Modules
Using a module is very simple.
Step 1: Create or Choose a Module
Python already provides many built-in modules.
Example:
math
random
datetime
You can also create your own module.
Easy2Siksha.com
Example:
calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Step 2: Import the Module
Use the import keyword.
import math
or
import calculator
Step 3: Use the Functions
import math
print(math.sqrt(25))
Output
5.0
Another example:
import calculator
print(calculator.add(5, 7))
Output
12
Step 4: Run the Program
Python loads the module into memory, and now all its functions are available for use.
Easy2Siksha.com
Diagram: Process of Using a Module
Need a Function
Choose/Create Module
Import Module
(import math)
Call Required Function
(math.sqrt(25))
Get Output
(5.0)
Advantages of Modules
Reduce duplicate code
Save programming time
Improve readability
Easy debugging
Better code organization
Easy sharing of code
Reusable in multiple projects
5. (b) How recursive functions are used for problem solving using Python? Illustrate.
A recursive function is a function that calls itself to solve a problem.
At first, this idea may sound confusing, but it is actually very simple.
Imagine you are standing at the bottom of a staircase with five steps.
Instead of saying,
"I will climb all five steps at once,"
you think,
"First climb one step, then do the same for the remaining steps."
This process repeats until no steps are left.
Easy2Siksha.com
That is exactly how recursion works.
What is a Recursive Function?
A recursive function is a function that repeatedly calls itself until a stopping condition,
known as the base case, is reached.
Every recursive function has two important parts:
1. Base Case
This is the condition that stops recursion.
Without it, the function would continue forever and cause an error.
2. Recursive Case
This is where the function calls itself with a smaller or simpler version of the problem.
Structure of a Recursive Function
Function
── Is Base Case True?
│ │
── Yes → Stop
│ │
│ └── No
Call Itself Again
Example: Factorial Using Recursion
The factorial of a number means:
5! = 5 × 4 × 3 × 2 × 1
Python Program
def factorial(n):
if n == 1:
Easy2Siksha.com
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output
120
How the Function Works
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1
= 120
Recursive Working Diagram
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
(Base Case)
Return 1
Easy2Siksha.com
2 × 1 = 2
3 × 2 = 6
4 × 6 = 24
5 × 24 = 120
Where Recursion is Used
Recursive functions are useful for solving problems that can be broken into smaller, similar
problems, such as:
Finding factorials
Fibonacci series
Tree and graph traversal
File and folder searching
Tower of Hanoi
Binary search (recursive implementation)
Advantages of Recursion
Makes complex problems easier to understand.
Produces shorter and cleaner code.
Well suited for tree and graph structures.
Breaks large problems into smaller sub-problems.
Disadvantages of Recursion
Can be slower than loops because of repeated function calls.
Uses more memory due to the function call stack.
Missing a proper base case can cause infinite recursion and a RecursionError.
Conclusion
Python modules help programmers organize code into reusable files, saving time and
making programs easier to manage and maintain. They allow developers to import ready-
made functions instead of writing everything from scratch.
Easy2Siksha.com
Recursive functions solve problems by repeatedly calling themselves until a base condition
is reached. They are especially useful for problems that naturally divide into smaller, similar
tasks, such as factorial calculations, Fibonacci numbers, and tree traversal. When used
correctly, recursion makes code elegant, readable, and easier to understand.
6.(a) How functions are called and passed by Python programs? Illustrate.
(b) Discuss the role of exception handling and its types.
Ans: 6(a) How are Functions Called and Passed in Python Programs? Illustrate.
A function in Python is a reusable block of code that performs a specific task. Instead of
writing the same code again and again, we write it once inside a function and call it
whenever needed. This makes the program shorter, easier to understand, and easier to
maintain.
Think of a function like a machine. You put something into the machine (input), it processes
it, and gives you an output.
Simple Diagram
Function Calling Process
Main Program
│ Calls Function
+--------------------+
| Function Block |
| Performs the Task |
+--------------------+
│ Returns Result
Main Program
1. Function Calling
When a function is defined, it does not execute automatically. It runs only when it is called.
Syntax
def function_name():
print("Welcome to Python")
function_name()
Easy2Siksha.com
Output
Welcome to Python
Explanation
def is used to define a function.
function_name() creates the function.
Writing function_name() later calls the function.
When called, Python moves to the function, executes its statements, and then
returns to the main program.
2. Passing Arguments to Functions
Often, a function needs some information to perform its work. This information is called an
argument or parameter.
Example:
def greet(name):
print("Hello", name)
greet("Rahul")
Output
Hello Rahul
Here,
name is the parameter.
"Rahul" is the argument passed during the function call.
3. Types of Passing Arguments in Python
Python allows different ways to pass values to functions.
(i) Positional Arguments
Arguments are passed in the same order as parameters.
def add(a, b):
print(a + b)
Easy2Siksha.com
add(10, 20)
Output
30
(ii) Keyword Arguments
The parameter names are mentioned while calling.
def student(name, age):
print(name, age)
student(age=20, name="Aman")
Output
Aman 20
The order does not matter because the parameter names are specified.
(iii) Default Arguments
A default value is assigned to a parameter.
def greet(name="Student"):
print("Hello", name)
greet()
greet("Priya")
Output
Hello Student
Hello Priya
If no value is passed, Python uses the default value.
(iv) Variable-Length Arguments
Sometimes we do not know how many values will be passed.
Easy2Siksha.com
def numbers(*num):
print(num)
numbers(10, 20, 30, 40)
Output
(10, 20, 30, 40)
The * collects all values into a tuple.
4. How Function Calling Works
Start Program
Function is Defined
Function is Called
Arguments are Passed
Function Executes
Result Returned
Program Continues
Advantages of Functions
Reduce repetition of code.
Make programs organized.
Improve readability.
Easier debugging and maintenance.
Code can be reused multiple times.
Conclusion
Functions are one of the most powerful features of Python. A function performs a specific
task only when it is called. Values can be passed to functions in different ways such as
positional, keyword, default, and variable-length arguments. Using functions makes Python
programs simpler, reusable, and more efficient.
Easy2Siksha.com
6(b) Discuss the Role of Exception Handling and Its Types
While writing programs, errors can occur at any time. For example, a user may enter the
wrong input, a file may not exist, or a number may be divided by zero. If these errors are not
handled, the program stops immediately.
Exception handling is a mechanism in Python that allows a program to detect such errors
and handle them gracefully without crashing.
Think of exception handling like a safety helmet while riding a bike. Even if an accident
happens, the helmet protects you from serious harm. Similarly, exception handling protects
a program from stopping unexpectedly.
What is an Exception?
An exception is an error that occurs during the execution of a program.
Example:
num = 10
print(num / 0)
Output
ZeroDivisionError
The program stops because division by zero is not allowed.
Why is Exception Handling Important?
Exception handling helps to:
Prevent sudden program crashes.
Display user-friendly error messages.
Continue program execution whenever possible.
Improve reliability and stability.
Make debugging easier.
Exception Handling Flow
Program Starts
Easy2Siksha.com
Statement Executes
Is an Error Found?
│ │
No Yes
│ │
▼ ▼
Continue Exception Raised
except Block Runs
finally Block (if present)
Program Ends
Keywords Used in Exception Handling
1. try
The code that may produce an error is written inside the try block.
try:
print(10/0)
2. except
Handles the error.
try:
print(10/0)
except:
print("Division by zero is not allowed.")
Output
Division by zero is not allowed.
3. else
Runs only if no exception occurs.
Easy2Siksha.com
try:
print(10/2)
except:
print("Error")
else:
print("Division successful")
Output
5.0
Division successful
4. finally
Always executes whether an exception occurs or not.
try:
print(10/2)
finally:
print("Program Finished")
Output
5.0
Program Finished
Types of Exceptions in Python
1. ZeroDivisionError
Occurs when dividing by zero.
10/0
2. NameError
Occurs when using a variable that has not been defined.
print(x)
3. TypeError
Occurs when incompatible data types are used together.
Easy2Siksha.com
"10" + 5
4. ValueError
Occurs when the value is invalid.
int("Hello")
5. IndexError
Occurs when accessing an invalid list index.
a = [1,2,3]
print(a[5])
6. KeyError
Occurs when a dictionary key does not exist.
student = {"name":"Rahul"}
print(student["age"])
7. FileNotFoundError
Occurs when a file is not found.
open("abc.txt")
Complete Example
try:
num = int(input("Enter a number: "))
print(100 / num)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter a valid number.")
finally:
print("Program Ended.")
Working
If the user enters 0, ZeroDivisionError is handled.
Easy2Siksha.com
If the user enters text like "abc", ValueError is handled.
The finally block runs every time.
Summary
Keyword
Purpose
try
Contains code that may cause an exception
except
Handles the exception
else
Executes if no exception occurs
finally
Executes whether an exception occurs or not
Conclusion
Exception handling is an essential feature of Python that allows programs to manage
runtime errors without crashing. By using try, except, else, and finally, programmers can
write robust and user-friendly applications. Common exceptions such as ZeroDivisionError,
ValueError, TypeError, NameError, IndexError, KeyError, and FileNotFoundError help
identify specific problems, making programs easier to debug and maintain. Proper exception
handling ensures that Python applications remain stable, reliable, and capable of dealing
with unexpected situations effectively.
SECTION-D
7 Discuss the following with examples:
(a) Strings processing
(b) Data processing
Ans: (a) String Processing
(b) Data Processing
This question asks you to explain two important concepts used in computer programming.
Although the names sound technical, the ideas are very simple. We use both string
processing and data processing almost every day whenever we use a mobile phone,
computer, website, or application.
(a) String Processing
What is a String?
Easy2Siksha.com
A string is simply a collection of characters written together. These characters may include
letters, numbers, symbols, or spaces.
For example:
"Hello"
"EasySiksha"
"Computer Science"
"12345"
Each of these is a string because it contains one or more characters.
Think of a string like a sentence written on paper. Just as we can erase, add, replace, or
rearrange words in a sentence, a computer can also perform many operations on strings.
What is String Processing?
String processing means performing different operations on text (strings) so that it becomes
useful or easier to understand.
Whenever a computer reads, edits, compares, or searches text, it is performing string
processing.
Simple Definition
String processing is the method of handling, modifying, searching, comparing, or analyzing
text data inside a computer program.
Everyday Example
Imagine you receive this message:
hello welcome to easysiksha
You want it to look professional.
After string processing, it becomes:
Hello Welcome to EasySiksha
The computer automatically changes the letters.
Easy2Siksha.com
Common String Processing Operations
1. Joining Strings (Concatenation)
Two strings can be joined together.
Example:
First Name = Rahul
Last Name = Sharma
Result:
Rahul Sharma
2. Finding Length
The computer counts how many characters are present.
Example:
Computer
Length = 8 characters
3. Converting Case
Changing uppercase to lowercase or vice versa.
Example:
easysiksha
becomes
EASYSIKSHA
or
EasySiksha
4. Searching
Finding a particular word inside a sentence.
Easy2Siksha.com
Example:
Welcome to EasySiksha
Search for:
EasySiksha
The computer quickly finds it.
5. Replacing
Changing one word into another.
Example:
Good Morning
Replace Morning
with
Evening
Result:
Good Evening
Diagram of String Processing
Input Text
+------------------+
| String Processing|
|------------------|
| Search |
| Replace |
| Join |
| Count Characters |
| Convert Case |
+------------------+
Modified Output
Easy2Siksha.com
Real-Life Examples of String Processing
Spell checking in Microsoft Word
Searching names in contact lists
Google Search
Password validation
Email address checking
Chat applications
SMS editing
Social media posts
Whenever text is handled by software, string processing is taking place.
(b) Data Processing
Now let's understand the second part.
What is Data?
Data means raw facts or information.
Examples:
Student marks
Employee salary
Mobile numbers
Temperature readings
Sales records
Raw data alone has little meaning until it is organized.
What is Data Processing?
Data processing is the process of collecting, organizing, calculating, storing, and presenting
data to produce meaningful information.
Simple Definition
Data processing is the process of converting raw data into useful information.
Easy2Siksha.com
Everyday Example
Suppose a teacher collects students' marks.
Raw Data:
Rahul - 78
Aman - 85
Priya - 92
Neha - 66
These are just numbers.
After processing, the computer calculates:
Highest marks
Lowest marks
Average marks
Pass or Fail
Class Rank
Now the data becomes useful information.
Steps of Data Processing
Step 1: Input
Data is entered.
Example:
Student Marks
Step 2: Processing
The computer performs calculations.
Examples:
Addition
Sorting
Comparing
Filtering
Calculating percentage
Easy2Siksha.com
Step 3: Output
Useful information is produced.
Example:
Average = 80%
Topper = Priya
Diagram of Data Processing
Raw Data
(Student Marks)
+----------------+
| Data Processing|
|----------------|
| Calculate |
| Sort |
| Filter |
| Compare |
| Store |
+----------------+
Useful Information
(Result, Report)
Real-Life Examples of Data Processing
Banking
Calculates account balance
Updates transactions
Prints statements
Hospitals
Stores patient records
Calculates medical bills
Generates reports
Easy2Siksha.com
Schools
Prepares report cards
Calculates attendance
Generates results
Shopping Websites
Calculate total bill
Apply discounts
Generate invoices
Weather Department
Processes temperature and rainfall data to prepare weather forecasts.
Difference Between String Processing and Data Processing
String Processing
Data Processing
Deals mainly with text or characters.
Deals with all kinds of data such as numbers,
text, dates, etc.
Performs operations like searching,
joining, replacing, and counting characters.
Performs operations like calculating, sorting,
filtering, storing, and analyzing data.
Used in text editors, messaging apps, and
search engines.
Used in banks, schools, hospitals,
businesses, and databases.
Output is modified or formatted text.
Output is meaningful information or reports.
Conclusion
String processing focuses on handling text data, such as searching, editing, joining, or
formatting words and sentences. It is widely used in applications like word processors,
messaging apps, search engines, and email systems.
On the other hand, data processing deals with all types of data, including numbers, text,
dates, and records. It converts raw data into meaningful information by performing
operations such as calculation, sorting, filtering, and analysis. This is essential in schools,
banks, hospitals, businesses, and many other organizations.
In simple words, string processing helps computers understand and manipulate text, while
data processing helps computers transform raw facts into useful information for better
decision-making.
Easy2Siksha.com
8. How the files are processed using Python? Discuss the use of write() and writelines()
functions.
Ans: Files are an important part of programming because they allow us to store data
permanently. Normally, when we run a Python program, the data is stored in the
computer's memory (RAM). Once the program ends, that data disappears. However, by
using files, we can save information so that it remains available even after the program is
closed.
Think of a file like a notebook. You can open the notebook, write something in it, close it,
and later open it again to read what you wrote. Python works with files in the same way.
What is File Processing?
File processing is the process of creating, opening, reading, writing, updating, and closing
files using a Python program.
For example:
Saving student records
Storing employee details
Writing exam results
Saving application logs
Creating reports
Instead of entering data every time the program runs, Python stores it inside a file.
Steps of File Processing in Python
Python follows a simple sequence while working with files.
Start
Open the File
Read or Write Data
Save the Changes
Close the File
Easy2Siksha.com
Every Python program that works with files generally follows these four steps.
Opening a File
Before performing any operation, Python must open the file.
Syntax
file = open("filename.txt", "mode")
Here:
filename.txt → Name of the file
mode → Specifies what operation we want to perform
Some common file modes are:
Mode
Purpose
"r"
Read the file
"w"
Write into the file (creates a new file or overwrites existing data)
"a"
Append data at the end of the file
"x"
Create a new file only if it does not already exist
The write() Function
The write() function is used to write a single string into a file.
Syntax
file.write("Text")
Example
file = open("student.txt", "w")
file.write("Rahul\n")
file.write("Age: 20")
file.close()
Output inside the file
Rahul
Age: 20
Easy2Siksha.com
How does write() work?
1. Open the file.
2. Python places the cursor at the beginning (or end if append mode is used).
3. The given string is written.
4. The file is closed after saving.
Important Features of write()
Writes only one string at a time.
If the file is opened in "w" mode, previous data is erased.
Returns the number of characters written.
Suitable for writing small amounts of text.
The writelines() Function
The writelines() function is used to write multiple strings together into a file.
Instead of calling write() many times, we can store several strings inside a list and write
them in one statement.
Syntax
file.writelines(list_of_strings)
Example
students = [
"Rahul\n",
"Aman\n",
"Priya\n"
]
file = open("student.txt", "w")
file.writelines(students)
file.close()
Output
Easy2Siksha.com
Rahul
Aman
Priya
Notice that each string contains \n (newline character). The writelines() function does not
automatically insert new lines. If \n is not included, all text will appear on the same line.
Example:
students = ["Rahul", "Aman", "Priya"]
Output:
RahulAmanPriya
Difference between write() and writelines()
write()
writelines()
Writes one string at a time
Writes multiple strings at once
Accepts only a single string
Accepts a list or iterable of strings
Often called multiple times
Usually called only once
Good for small text
Better for writing many lines efficiently
Returns the number of characters
written
Does not return the total number of
characters
Real-Life Example
Imagine a teacher wants to save students' names.
Using write()
file.write("Rahul\n")
file.write("Aman\n")
file.write("Priya\n")
The teacher writes each name one by one.
Using writelines()
names = [
"Rahul\n",
"Aman\n",
"Priya\n"
]
file.writelines(names)
Easy2Siksha.com
Here, the teacher prepares the entire list first and writes everything together in a single
step.
Why is close() Important?
After completing file operations, we should always close the file.
file.close()
Closing the file:
Saves all changes.
Frees system resources.
Prevents data loss.
Allows other programs to access the file safely.
Summary Diagram
Python File Processing
Open the File
┌───────────────────────┐
│ Read Data (r) │
│ Write Data (w) │
│ Append Data (a) │
└───────────────────────┘
write() → Write one string
writelines() → Write multiple strings
from a list
Close the File
Conclusion
File processing in Python enables programs to store data permanently so it can be used
again even after the program ends. The process involves opening, reading or writing, and
closing a file. The write() function is used to write a single string, making it suitable for small
amounts of text, while the writelines() function writes multiple strings from a list, making it
more convenient when saving several lines at once. Understanding these functions is
Easy2Siksha.com
essential because file handling is widely used in real-world applications such as storing
student records, employee information, reports, and application data.
“This paper has been carefully prepared for educational purposes. If you notice any mistakes or
have suggestions, feel free to share your feedback.”